﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Expression.Samples.Interactivity.DataHelpers;
using XamlingCore.SL.Controls.ContentTemplate.Interfaces;

namespace XamlingCore.SL.Controls.ContentTemplate
{
    [ContentProperty("Template")]
    public class ObjectContentTemplateSelector : DependencyObject, IContentTemplatePointer
    {
        public string Value { get; set; }
        public string TemplateKey { get; set; }
        private DataTemplate template;



        public DataTemplate Template
        {
            get
            {
                if(template!=null)
                {
                    return template;
                }
                
                if(TemplateKey!=null)
                {
                    return Application.Current.Resources[TemplateKey] as DataTemplate;    
                }

                return null;
                
            }
            set
            {
                template = value;
            }
        }

        public bool IsValid(object targetValue)
        {
            if (Value == "*" || string.IsNullOrEmpty(Value))
            {
                return true;
            }
            if(targetValue == null)
            {
                return Value.ToLower() == "null";
            }

            if (Value.ToLower() == "null")
            {
                return targetValue == null;
            }

            var type = targetValue.GetType().FullName;

            if(type.EndsWith(Value))
            {
                return true;
            }

            if (targetValue == null || this.Value == null)
                return object.Equals(targetValue, this.Value);

            object convertedValue = ConverterHelper.ConvertToType(this.Value, targetValue.GetType());
            return object.Equals(targetValue, ConverterHelper.ConvertToType(this.Value, targetValue.GetType()));
        }
    }
}
